package cn.com.inossem.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import cn.com.inossem.adapter.BaGuaDetailsAdapter;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.fragment.BaGuaFragment;
import cn.com.inossem.model.AddBaGuaInfoBean;
import cn.com.inossem.model.BaGuaListInfoBean;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;

/**
 * 
 * 八卦详情
 * 
 * <p>
 * detailed comment
 * 
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
public class BaGuaDetailsActivity extends RequestActivity {

	ListView list_view = null;
	BaGuaDetailsAdapter adapter;
	EditText editText;
	ImageView more, back, buttompic, imgsave;
	RelativeLayout rlayout, huaminglayout, shiminglayout;

	boolean isFlag = false;

	private int position;
	private int page = 1;
	boolean sendmessage = true;

	public List<BaGuaListInfoBean> messageInfo;
	ImageView shimingpic, huamingpic, shimingxuanze, huamingxuanze;
	TextView shimingtext, huamingtext;
	LinearLayout main_dialog_layout, main_dialog_layout1, llayout01, llayout02,
			llayout03;

	boolean resultflag = true;
	boolean flag = false;

	private Handler handler = new Handler() {

		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			super.dispatchMessage(msg);
			switch (msg.what) {
			case 1:
				String str = msg.getData().get("id").toString();
				launchRequest(WooRequestFactory.zanJiekou("", str));
				adapter.notifyDataSetChanged();
				break;
			case 2:
				str = msg.getData().get("id").toString();
				launchRequest(WooRequestFactory.baguahuifudel(str));
				for (int i = 0; i < messageInfo.size(); i++) {
					if (messageInfo.get(i).getId().equals(str)) {
						messageInfo.remove(messageInfo.get(i));
					}
				}
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}

	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main_tab_layout);
		getInfo();
		initView();

	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {

		messageInfo = new ArrayList<BaGuaListInfoBean>();
		position = getIntent().getIntExtra("position", 0);

		main_dialog_layout = (LinearLayout) this
				.findViewById(R.id.main_dialog_layout);
		main_dialog_layout1 = (LinearLayout) this
				.findViewById(R.id.main_dialog_layout1);

		llayout01 = (LinearLayout) this.findViewById(R.id.llayout01);
		llayout01.setOnClickListener(this);
		llayout02 = (LinearLayout) this.findViewById(R.id.llayout02);
		llayout02.setOnClickListener(this);
		llayout03 = (LinearLayout) this.findViewById(R.id.llayout03);
		llayout03.setOnClickListener(this);

		imgsave = (ImageView) this.findViewById(R.id.imgsave);
		imgsave.setOnClickListener(this);
		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);
		more = (ImageView) this.findViewById(R.id.more);
		more.setOnClickListener(this);
		buttompic = (ImageView) this.findViewById(R.id.buttompic);
		buttompic.setOnClickListener(this);
		rlayout = (RelativeLayout) this.findViewById(R.id.rlayout);
		rlayout.setOnClickListener(this);
		list_view = (ListView) this.findViewById(R.id.listview);
		list_view.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) { // 当不滚动时
				case OnScrollListener.SCROLL_STATE_IDLE: // 判断滚动到底部
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						if (resultflag) {
							resultflag = false;
							page++;
							launchRequest(WooRequestFactory.getBagualist("",
									page + "",
									BaGuaFragment.messageInfo.get(position)
											.getId()));
						}
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});

		editText = (EditText) this.findViewById(R.id.editText111);
		editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);

		huaminglayout = (RelativeLayout) this.findViewById(R.id.huaminglayout);
		huaminglayout.setOnClickListener(this);
		shiminglayout = (RelativeLayout) this.findViewById(R.id.shiminglayout);
		shiminglayout.setOnClickListener(this);
		shimingpic = (ImageView) this.findViewById(R.id.shimingpic);
		if (!Utils.messageInfo.userInfo.getImageData().equals("")) {
			shimingpic.setBackgroundDrawable(new BitmapDrawable(Utils
					.toRoundCorner(stringtoBitmap(Utils.messageInfo.userInfo
							.getImageData()), 50)));
		}
		huamingpic = (ImageView) this.findViewById(R.id.huamingpic);
		huamingpic.setBackgroundResource(getResource(picname));
		shimingtext = (TextView) this.findViewById(R.id.shimingtext);
		shimingtext.setText("实名：" + Utils.messageInfo.userInfo.getTruename());
		huamingtext = (TextView) this.findViewById(R.id.huamingtext);
		huamingtext.setText("花名：" + name);
		shimingxuanze = (ImageView) this.findViewById(R.id.shimingxuanze);
		huamingxuanze = (ImageView) this.findViewById(R.id.huamingxuanze);

		if (ishuaming) {
			namehuifu = name;
			pichuifu = picname;
			buttompic.setBackgroundResource(getResource(picname));
			huamingxuanze.setVisibility(View.VISIBLE);
			shimingxuanze.setVisibility(View.GONE);
		} else {
			shimingxuanze.setVisibility(View.VISIBLE);
			huamingxuanze.setVisibility(View.GONE);
			if (!Utils.messageInfo.userInfo.getImageData().equals("")) {
				namehuifu = Utils.messageInfo.userInfo.getTruename();
				pichuifu = Utils.messageInfo.userInfo.getImageData();
				buttompic.setBackgroundDrawable(new BitmapDrawable(Utils
						.toRoundCorner(
								stringtoBitmap(Utils.messageInfo.userInfo
										.getImageData()), 50)));
			}
		}

		editText.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (event != null
						&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
					System.out.println("actionId:" + actionId + "=="
							+ EditorInfo.IME_ACTION_SEARCH);
					// actionId == EditorInfo.IME_ACTION_SEARCH
					// || (event != null && event.getKeyCode() ==
					// KeyEvent.KEYCODE_ENTER)
					// do something;
					if (sendmessage) {
						sendmessage = false;
						if (!editText.getText().toString().equals("")
								&& !Utils.messageInfo.userInfo.getTruename()
										.equals("")) {

							if ((!Utils.messageInfo.userInfo.getImageData()
									.equals("") && !ishuaming) || ishuaming) {
								AddBaGuaInfoBean bean = new AddBaGuaInfoBean();
								bean.setParentID(BaGuaFragment.messageInfo.get(
										position).getId());
								bean.setText(editText.getText().toString());
								String hint = editText.getHint().toString();
								String replyMsg = editText.getText().toString();
								if (hint.startsWith("回复")) {
									replyMsg = hint + replyMsg;
								}
								launchRequest(WooRequestFactory
										.addBaguaHuifu(
												BaGuaFragment.messageInfo.get(
														position).getId(),
												namehuifu, replyMsg, pichuifu));
							} else {
								Toast.makeText(BaGuaDetailsActivity.this,
										"头像，实名和内容不能为空！", Toast.LENGTH_LONG)
										.show();
							}
						} else {
							Toast.makeText(BaGuaDetailsActivity.this,
									"头像，实名和内容不能为空！", Toast.LENGTH_LONG).show();
						}
					} else {
						sendmessage = true;
					}
					return true;
				}
				return false;
			}
		});

		adapter = new BaGuaDetailsAdapter(this,
				BaGuaFragment.messageInfo.get(position), messageInfo, handler);
		list_view.setAdapter(adapter);

		launchRequest(WooRequestFactory.getBagualist("", page + "",
				BaGuaFragment.messageInfo.get(position).getId()));
	}

	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	String name;
	String namehuifu;
	String picname;
	String pichuifu;
	boolean ishuaming = true;

	private void getInfo() {
		SharedPreferences settings = this
				.getSharedPreferences("shared_file", 0);
		// 第二个参数为如果SharedPreferences中没有保存就赋一个默认值
		int random = (int) (Math.random() * Utils.niming.length);
		name = settings.getString("name", Utils.niming[random]);
		int picrandom = 1 + (int) (Math.random() * 16);
		picname = settings.getString("picname", "h" + picrandom);

		System.out.println("picname::::::" + picname);
		ishuaming = settings.getBoolean("ishuaming", true);
	}

	private void setInfo(String key, boolean value) {
		// 获得SharedPreferences对象
		SharedPreferences settings = this
				.getSharedPreferences("shared_file", 0);

		// 获得可编辑对象
		SharedPreferences.Editor editor = settings.edit();

		editor.putBoolean(key, value);

		editor.commit();
	}

	/**
	 * 获取图片名称获取图片的资源id的方法
	 * 
	 * @param imageName
	 * @return
	 */
	public int getResource(String imageName) {
		int resId = getResources().getIdentifier(imageName, "drawable",
				getPackageName());
		return resId;
	}

	@Override
	public Request getInitialRequest() {
		return null;

	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		resultflag = true;
		if (bundle.containsKey(WooRequestFactory.RESPONSE_BAGUALIST_DATA)) {
			List<BaGuaListInfoBean> retList = bundle
					.getParcelableArrayList(WooRequestFactory.RESPONSE_BAGUALIST_DATA);
			if (retList.size() > 0) {
				messageInfo.addAll(retList);

				System.out.println("长度：" + messageInfo.size());
				if (adapter == null) {
					adapter = new BaGuaDetailsAdapter(this,
							BaGuaFragment.messageInfo.get(position),
							messageInfo, handler);
					list_view.setAdapter(adapter);
					adapter.notifyDataSetChanged();
				} else {
					adapter.notifyDataSetChanged();
				}

				adapter.setTotal(bundle.getInt("total"));
			}
		} else if (bundle
				.containsKey(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS) == 1) {
				editText.setText("");
				page = 1;
				messageInfo.clear();
				adapter = null;
				launchRequest(WooRequestFactory.getBagualist("", page + "",
						BaGuaFragment.messageInfo.get(position).getId()));

				if (getCurrentFocus() != null) {
					((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
							.hideSoftInputFromWindow(getCurrentFocus()
									.getWindowToken(),
									InputMethodManager.HIDE_NOT_ALWAYS);
				}
			} else {
				Toast.makeText(this, "发布失败!", Toast.LENGTH_LONG).show();
			}
		} else if (bundle
				.containsKey(WooRequestFactory.BUNDLE_EXTRA_DELSUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_DELSUCCESS) == 1) {
				Toast.makeText(this, "删除成功！", Toast.LENGTH_LONG).show();
				setResult(2);
				finish();
			}
		}
	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.baguadetails_layout;

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			setResult(1);
			finish();

			return true;

		}

		return super.onKeyDown(keyCode, event);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.huaminglayout:
			setInfo("ishuaming", true);
			ishuaming = true;
			namehuifu = name;
			pichuifu = picname;
			huamingxuanze.setVisibility(View.VISIBLE);
			shimingxuanze.setVisibility(View.GONE);
			buttompic.setBackgroundResource(getResource(picname));
			isFlag = false;
			editText.setHint("匿名评论");
			rlayout.setVisibility(View.GONE);
			break;
		case R.id.shiminglayout:
			setInfo("ishuaming", false);
			ishuaming = false;
			shimingxuanze.setVisibility(View.VISIBLE);
			huamingxuanze.setVisibility(View.GONE);
			editText.setHint("实名评论");

			if (!Utils.messageInfo.userInfo.getImageData().equals("")) {
				namehuifu = Utils.messageInfo.userInfo.getTruename();
				pichuifu = Utils.messageInfo.userInfo.getImageData();
				buttompic.setBackgroundDrawable(new BitmapDrawable(Utils
						.toRoundCorner(
								stringtoBitmap(Utils.messageInfo.userInfo
										.getImageData()), 50)));
			} else {
				namehuifu = Utils.messageInfo.userInfo.getTruename();
				pichuifu = "";
				buttompic.setBackgroundResource(R.drawable.touxiang);
			}
			isFlag = false;
			rlayout.setVisibility(View.GONE);
			break;
		case R.id.back:
			setResult(1);
			finish();
			break;
		case R.id.llayout01:
			flag = false;
			main_dialog_layout.setVisibility(View.GONE);
			main_dialog_layout1.setVisibility(View.GONE);
			Intent intent = new Intent(this, JuBaoActivity.class);
			intent.putExtra("gossipID", BaGuaFragment.messageInfo.get(position)
					.getId());
			startActivity(intent);
			break;
		case R.id.llayout02:
			launchRequest(WooRequestFactory.delbagua(BaGuaFragment.messageInfo
					.get(position).getId()));
			break;
		case R.id.llayout03:
			flag = false;
			main_dialog_layout.setVisibility(View.GONE);
			main_dialog_layout1.setVisibility(View.GONE);
			intent = new Intent(this, JuBaoActivity.class);
			intent.putExtra("gossipID", BaGuaFragment.messageInfo.get(position).getId());
			startActivity(intent);
			break;

		case R.id.more:
			// Intent intent = new Intent(this, JuBaoActivity.class);
			// startActivity(intent);
			if (BaGuaFragment.messageInfo.get(position).getIsMeSend()
					.equals("1")) {
				if (flag) {
					flag = false;
					main_dialog_layout.setVisibility(View.GONE);
					main_dialog_layout1.setVisibility(View.GONE);
				} else {
					flag = true;
					main_dialog_layout.setVisibility(View.VISIBLE);
				}
			} else {
				if (flag) {
					flag = false;
					main_dialog_layout.setVisibility(View.GONE);
					main_dialog_layout1.setVisibility(View.GONE);
				} else {
					flag = true;
					main_dialog_layout1.setVisibility(View.VISIBLE);
				}
			}
			break;
		case R.id.rlayout:
			if (isFlag) {
				isFlag = false;
				rlayout.setVisibility(View.GONE);
			} else {
				isFlag = true;
				rlayout.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.buttompic:
			if (isFlag) {
				isFlag = false;
				rlayout.setVisibility(View.GONE);
			} else {
				isFlag = true;
				rlayout.setVisibility(View.VISIBLE);
			}
			break;
		default:
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 1:
			setResult(1);
			finish();
		default:
			break;
		}
	}
}
